package com.zjun.demo.experimentaldemo.signal_strength

import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiInfo
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.zjun.demo.experimentaldemo.R
import com.zjun.demo.experimentaldemo.base.BaseActivity
import com.zjun.demo.experimentaldemo.databinding.ActivitySignalStrengthBinding
import java.lang.ref.WeakReference

/**
 * 网络信号强度监听
 *
 * 需要权限
 * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 *
 */
class SignalStrengthActivity : BaseActivity<ActivitySignalStrengthBinding>() {

    private var mSignalStrengthHandler: SignalStrengthHandler? = null

    private val request = NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .build()

    private lateinit var connectivityManager: ConnectivityManager

    private lateinit var networkCallback: ConnectivityManager.NetworkCallback

    override fun getLayoutId(): Int = R.layout.activity_signal_strength

    override fun initialize() {
        connectivityManager = getSystemService(ConnectivityManager::class.java)
        networkCallback = @RequiresApi(Build.VERSION_CODES.S)
        object : ConnectivityManager.NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) {

            override fun onAvailable(network: Network) {}

            override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    runOnUiThread {
                        val wifiInfo = networkCapabilities.transportInfo as WifiInfo
                        "wifi名称: ${wifiInfo.ssid}\n信号强度 = ${networkCapabilities.signalStrength}".also { mBinding.wifiInfo.text = it }
                    }
                }
            }
        }

        if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(ACCESS_FINE_LOCATION), 1)
        } else {
            mSignalStrengthHandler = SignalStrengthHandler(this)
            mSignalStrengthHandler?.sendEmptyMessage(0)
        }
    }

    fun requestCallBack() {
        try {
            connectivityManager.unregisterNetworkCallback(networkCallback)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        connectivityManager.requestNetwork(request, networkCallback)
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            connectivityManager.unregisterNetworkCallback(networkCallback)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        mSignalStrengthHandler?.removeCallbacksAndMessages(null)
        mSignalStrengthHandler = null
    }

    class SignalStrengthHandler(activity: SignalStrengthActivity) : Handler(Looper.getMainLooper()) {

        private var mWeakReference: WeakReference<SignalStrengthActivity?> = WeakReference(activity)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            removeMessages(0)
            val signalStrengthActivity = mWeakReference.get()
            signalStrengthActivity?.requestCallBack()
            sendEmptyMessageDelayed(0, 1000)
        }

    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            mSignalStrengthHandler = SignalStrengthHandler(this)
            mSignalStrengthHandler?.sendEmptyMessage(0)
        }
    }

}